-- 定义两个相似的类A和B A = {foo1 = 123, name = "A"} A.__index = A B = {foo2 = 456, name = "B"} B.__index = B
functionA:new() local re = {} setmetatable(re, self) return re end
functionA:GetName() print(self.name) end
functionB:new() local re = {} setmetatable(re, self) return re end
functionB:GetName() print(self.name) end
functionB:MethodOnB() print("method on B") end
-- 定义类C,继承自A和B C = {} functionC:new() local childA = A:new() local childB = B:new() local re = {} setmetatable(re, { __index = function(table, key) if childA[key] then return childA[key] elseif childB[key] then return childB[key] else return"not found" end end }) return re end
-- 定义加法行为 meta = {__add = function(A, B) local re = {} for _, val inipairs(A) do table.insert(re, val) end for _, val inipairs(B) do table.insert(re, val) end return re end } a = setmetatable({1, 2, 3}, meta) b = setmetatable({4, 5, 6}, meta)